var t = require('hy5b/t')
var write = require('hy5b/backend/write')
var pathRead = require('hy5b/backend/path-read')
var path = require('path');


function main() {
  var argvs = process.argv;

  if (argvs.length < 3)
    console.log("Usage: " + path.basename(argvs[0]) + " " + path.basename(argvs[1]) + " {file or path} {except ...}");
  else
    findInFileAndReplace(argvs[2], argvs.slice(3));
}

function findInFileAndReplace(fileOrPath, excepts) {
  pathRead(fileOrPath, findAndReplace, complete, excepts)
}

var count = 0
var count1 = 0

function complete() {
  console.log('find', count)
  console.log('replace', count1)
}

function findAndReplace(err, str, file) {
  if (!err) {
    if (/class [^ ]+ extends Component/.test(str)) { // 是 class X extends Component 写法
      if (/\{ *this\.[^\.]+\.bind\(this\) *\}/.test(str)) { //有 {this.xxx.bind(this)}
        count++;
        var newStr = str;
        var willAdd = []
        t.matchAll(str, /\{ *(this\.([^\.]+)\.bind\(this\)) *\}/, function(match) { //找到 {this.xxx.bind(this)} 并存起来
          var newFn = 'this.binded' + t(match.match[2]).toProperCase();
          willAdd.push(newFn + ' = ' + match.match[1])
          newStr = newStr.replace(match.match[0], '{' + newFn + '}');
        })
        var match;
        if (match = /^ *constructor\(.*\) \{ *$[\r\n]+^( *)super\(.*\)[; ]*$[\r\n]+/m.exec(newStr)) {// 有 constructor
          count1++;
          newStr = newStr.replace(match[0], match[0] + match[1] + willAdd.join('\r\n' + match[1]) + '\r\n');
        } else if (match = /^( *)render *\(\) \{/m.exec(newStr)) {//没有就找 render() {}
          count1++;
          var innerSpace = match[1] + '  ';
          newStr = newStr.replace(match[0], match[1] + 'constructor() {\r\n'
            + innerSpace + 'super()\r\n'
            + innerSpace + willAdd.join('\r\n' + innerSpace) + '\r\n' + match[1] + '}\r\n' + match[0]);
        } else {
          console.log(file)
        }
        var fs = write(file + '.test.js')
        fs.write(newStr)
      }
    }
  }
}

main()